package com.game.ghost.webapp.apps.service.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.game.ghost.webapp.apps.service.CacheManager;

/**
 * This class provides cache implementation for caching objects that can be reused. It uses simple HashMap internally.
 * No memory cleaning algorithm is provided yet for this implementation, still it offers interface to clear cache in case 
 * required via clearCache() method.
 * 
 * @author gautak
 *
 */
@Component("localCache")
public class LocalCacheManagerImpl implements CacheManager {
	
	private static final Log log = LogFactory.getLog(LocalCacheManagerImpl.class);
	
	private Map<String, Map<String, Serializable>> cache = new HashMap<String, Map<String, Serializable>>();
	
	public void add(String cacheName, String cacheKey, Serializable object){
		
		Map<String, Serializable> map = cache.get(cacheName);
		
		if(null == map){
			map = new HashMap<String, Serializable>();
			cache.put(cacheName, map);
		}
		
		map.put(cacheKey, object);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T get(String cacheName, String cacheKey, T t){
		
		T value = null;
		
		Map<String, Serializable> map = cache.get(cacheName);
		
		if(null == map){
			return null;
		}
		
		value = (T) map.get(cacheKey);
		
		return value;
		
	}
	
	public void clearCache(){ 
		cache.clear();
	}

}
